package com.itheima.consultant.config.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.consultant.entity.constant.FileConstant;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

//这个与RedisChatMemoryStore二选一
//具体配置在CommonConfig的chatMemoryProvider中
@Slf4j
@Component
@RequiredArgsConstructor
public class FileChatMemoryStore implements ChatMemoryStore {
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final String basePath = FileConstant.FILE_DATA;

    private String getFilePath(Object memoryId) {
        return basePath + "history-" + memoryId + ".json";
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String filePath = getFilePath(memoryId);
        File file = new File(filePath);

        if (!file.exists()) {
            return new ArrayList<>();
        }

        try {
            String json = Files.readString(Paths.get(filePath));
            return ChatMessageDeserializer.messagesFromJson(json);
        } catch (IOException e) {
            throw new RuntimeException("Failed to read messages from file", e);
        }
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> list) {
        String filePath = getFilePath(memoryId);
        String json = ChatMessageSerializer.messagesToJson(list);

        try {
            Files.write(Paths.get(filePath), json.getBytes());
        } catch (IOException e) {
            throw new RuntimeException("Failed to write messages to file", e);
        }
    }

    @Override
    public void deleteMessages(Object memoryId) {
        String filePath = getFilePath(memoryId);
        File file = new File(filePath);

        if (file.exists()) {
            try {
                Files.delete(Paths.get(filePath));
            } catch (IOException e) {
                throw new RuntimeException("Failed to delete messages file", e);
            }
        }
    }
}
